package org.auf.core;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class View implements IView {

	private VelocityEngine velocity ;
	private HttpServletResponse response;
	private HttpServletRequest request;
	private VelocityContext context;
	private Template template;

	public boolean load(String temprequest) {
		try {
			template = velocity.getTemplate(temprequest + ".vm");
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	public void assignVar(String var, String value) {
		context.put(var, value);
	}
	
	public void assignVar(String var, Object obj) {
		context.put(var, obj);
	}
	
	
	public void show() {
		StringWriter writer = new StringWriter();

		try {
			template.merge(context, writer);
			PrintWriter out = response.getWriter();
			out.println(writer.toString());

		} catch (ResourceNotFoundException e) {
			e.printStackTrace();
		} catch (ParseErrorException e) {
			e.printStackTrace();
		} catch (MethodInvocationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public View(HttpServletRequest request, HttpServletResponse response, HttpServlet servlet) {
		try {
			//Ruta relativa en formato unix del root folder
			String path = servlet.getServletContext().getRealPath("/").replace("\\", "/") + "WEB-INF/view/";
			
			//Inicializa el engine y lo configura adecuadamente
			velocity = new VelocityEngine();
			velocity.setProperty(Velocity.RESOURCE_LOADER, "file");
			velocity.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
			velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
			
			velocity.init();
			
			context = new VelocityContext();
			
			this.request = request;
			this.response = response;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
